from rest_framework import serializers
from rest_framework.serializers import ModelSerializer,IntegerField
from django.db import transaction

from celery_tasks.static_files.tasks import get_detail_html
from goods.models import SKU, GoodsCategory, SPUSpecification, SpecificationOption, SKUSpecification

class SKUSpecificationSerializer(serializers.ModelSerializer):
    option_id = serializers.IntegerField()
    spec_id = serializers.IntegerField()
    class Meta:
        model = SKUSpecification
        fields =('spec_id','option_id')

class SKUserializer(ModelSerializer):
    # spu_id = IntegerField()
    # category_id =IntegerField()
    # specs = SKUSpecificationSerializer(read_only=True,many=True)

    # 指定所关联的选项信息 关联嵌套返回
    specs = SKUSpecificationSerializer(read_only=True, many=True)
    # 指定分类信息
    category_id = serializers.IntegerField()
    # 关联嵌套返回
    category = serializers.StringRelatedField(read_only=True)
    # 指定所关联的spu表信息
    spu_id = serializers.IntegerField()
    # 关联嵌套返回
    spu = serializers.StringRelatedField(read_only=True)
    class Meta:
        model = SKU
        fields = '__all__'
        read_only_fields=('category','spu')

    def create(self, validated_data):
        specs = self.context['request'].data.get('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                # specs = sku.spu.specs
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku,spec_id=spec['spec_id'],option_id=spec['option_id'])
            except Exception as e:
                transaction.savepoint_rollback(save_point)
                raise serializers.ValidationError('保存数据失败')
            else:
                transaction.savepoint_commit(save_point)
                get_detail_html.delay(sku.id)
                return sku
    def update(self, instance, validated_data):
        specs = self.context['request'].data.get('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                res = SKU.objects.filter(id=instance.id).update(**validated_data)
                # print('更新信息 %s'%res)
                # specs = sku.spu.specs
                for spec in specs:
                    SKUSpecification.objects.filter(sku=instance).update(**spec)
            except Exception as e:
                transaction.savepoint_rollback(save_point)
                raise serializers.ValidationError('保存数据失败')
            else:
                transaction.savepoint_commit(save_point)
                get_detail_html.delay(instance.id)
                return instance


class GoodsCategoryserializer(ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = '__all__'

class SpecificationOptionSerializer(ModelSerializer):

    class Meta:
        model = SpecificationOption
        fields = "__all__"

class SPUSpecificationSerializer(ModelSerializer):
    options = SpecificationOptionSerializer(many=True)
    class Meta:
        model = SPUSpecification
        fields = "__all__"